<template>
  <div class="app-container">
    <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="100px" class="demo-ruleForm dict-form">
      <el-card shadow="never" header="账号信息">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="用户账号" prop="loginName">
                <el-input v-model="formData.loginName" disabled="disabled" />
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="用户名称" prop="realName">
                <el-input v-model="formData.realName" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <el-card shadow="never" header="基本信息" style="margin-top: 10px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="" prop="header">
                <el-upload
                  v-model="formData.header"
                  class="avatar-uploader"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="formData.header" :src="formData.header" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12" style="margin-top:24px;">
            <div class="grid-content bg-purple">
              <el-form-item label="所属部门">
                <el-select v-model="formData.deptIds" filterable multiple>
                  <el-option
                    v-for="item in depts"
                    :key="item.id"
                    :label="item.deptName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="性别" prop="gender">
                <el-select v-model="formData.gender">
                  <el-option
                    v-for="item in gends"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  />
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="身份证" prop="identityNo">
                <el-input v-model="formData.identityNo" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="formData.email" />
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="职位" prop="position">
                <el-select
                  v-if="positions"
                  v-model="formData.position"
                  filterable
                >
                  <el-option
                    v-for="item in positions"
                    :key="item.itemKey"
                    :label="item.itemValue"
                    :value="item.itemKey"
                  />
                </el-select>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="联系方式" prop="mobile">
                <el-input v-model="formData.mobile" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="是否禁用" prop="status">
                <el-switch
                  v-model="formData.status"
                  :active-value="activeValue"
                  :inactive-value="inactiveValue"
                />
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="16">
            <div class="grid-content bg-purple">
              <el-form-item label="地址" prop="address">
                <el-input v-model="formData.address" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="16">
            <div class="grid-content bg-purple">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark" type="textarea" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <el-card shadow="never" header="角色信息" style="margin-top: 10px;">
        <el-row :gutter="20" v-if="formData.roles.length>0">
          <el-col :span="24">
            <div class="grid-content bg-purple">
              <el-form-item label="">
                <el-checkbox-group v-model="formData.roles">
                  <el-checkbox v-for="item in roles" v-if="roles" :label="item.roleCode">
                    {{ item.roleName }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <el-form-item style="text-align: center;margin-top: 40px;">
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="$router.back(-1)">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { getDataById, save } from '@/api/org/user/index'
  import { getAllRoleByOrgId } from '@/api/sys/auth/role/index'
  import { getAllDeptByOrgId } from '@/api/org/dept/index'
  import { getItemByDictKey } from '@/api/sys/dict/item/index'
  import { validEmail } from '@/utils/validate'

  export default {
  data() {
    const validMail = (rule, value, callback) => {
      if (!validEmail(this.formData.email)) {
        callback(new Error('邮箱不合法，请重新输入'))
      } else {
        callback()
      }
    }
    return {
      formData: {
        loginName: '',
        realName: '',
        header: '',
        deptIds: [],
        gender: '',
        identityNo: '',
        email: '',
        position: '',
        mobile: '',
        address: '',
        remark: '',
        status: '',
        roles: []
      },
      rules: {
        realName: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        loginName: [
          { required: true, message: '请输入用户账号', trigger: 'blur' },
          { min: 3, max: 100, message: '长度在 3 到 100 个字符', trigger: 'blur' }
        ],
        email: [
          { validator: validMail, trigger: 'blur' }
        ]
      },
      gends: [
        {
          key: 1,
          value: '男'
        },
        {
          key: 0,
          value: '女'
        },
        {
          key: 2,
          value: '未知'
        }
      ],
      roles: [],
      depts: [],
      positions: [],
      activeValue: 1,
      inactiveValue: 0
    }
  },
  created() {
    if (this.$route.query.id) {
      this.getDataById()
      this.getAllRoleByOrgId()
      this.getAllDeptByOrgId()
      this.getPosition('position')
    } else {
      this.$router.push({ name: 'user_mgr_list' })
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          save(this.formData).then(() => {
            this.loading = false
            this.$router.push({ name: 'user_mgr_list' })
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    getAllRoleByOrgId() {
      getAllRoleByOrgId().then(res => {
        this.roles = res.data
      })
    },
    getAllDeptByOrgId() {
      getAllDeptByOrgId().then(res => {
        this.depts = res.data
      })
    },
    getPosition(dictKey) {
      getItemByDictKey(dictKey).then(res => {
        this.positions = res.data
      })
    },
    getDataById() {
      getDataById(this.$route.query.id).then(res => {
        this.formData = res.data
      })
    },
    handleAvatarSuccess(res, file) {
      this.formData.header = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style scoped>
  .dict-form{
    padding-top: 20px;
    padding-right: 20px;
    padding-left: 20px;
  }
  .title-span{
    margin-top: 15px;
  }
  .hr-div{
    height: 1px;
    background: #dfe6ec;
    margin-bottom: 30px;
    margin-top: 10px;
  }
  .avatar-uploader {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    line-height: 90px;
    text-align: center;
    border: #dfe6ec solid 1px;
  }
  .avatar {
    width: 90px;
    height: 90px;
    display: block;
  }
</style>
